/**
 * 渲染性能测试工具
 * 专门用于测试DataLineage组件的渲染优化效果
 */

interface RenderingTestResult {
  componentName: string;
  renderCount: number;
  testDuration: number;
  passed: boolean;
  issues: string[];
  recommendations: string[];
}

class RenderingPerformanceTest {
  private renderCounts = new Map<string, number>();
  private testStartTime = 0;
  private originalConsoleLog: typeof console.log;

  constructor() {
    this.originalConsoleLog = console.log;
  }

  /**
   * 开始监控渲染次数
   */
  startMonitoring(componentName: string): void {
    this.testStartTime = Date.now();
    this.renderCounts.set(componentName, 0);

    // 拦截console.log来统计渲染次数
    console.log = (...args: any[]) => {
      const message = args[0];
      if (typeof message === 'string' && message.includes(`🔄 ${componentName} 渲染次数:`)) {
        const match = message.match(/渲染次数: (\d+)/);
        if (match) {
          const count = parseInt(match[1], 10);
          this.renderCounts.set(componentName, count);
        }
      }
      return this.originalConsoleLog.apply(console, args);
    };
  }

  /**
   * 停止监控并生成测试报告
   */
  stopMonitoring(componentName: string): RenderingTestResult {
    const testDuration = Date.now() - this.testStartTime;
    const renderCount = this.renderCounts.get(componentName) || 0;
    
    // 恢复原始console.log
    console.log = this.originalConsoleLog;

    const issues: string[] = [];
    const recommendations: string[] = [];

    // 性能标准：初始加载最多3次渲染
    const maxAllowedRenders = 3;
    const passed = renderCount <= maxAllowedRenders;

    if (!passed) {
      issues.push(`渲染次数过多: ${renderCount}次 (期望: ≤${maxAllowedRenders}次)`);
      
      if (renderCount > 10) {
        recommendations.push('检查是否有不必要的状态更新导致频繁重新渲染');
        recommendations.push('使用React.memo优化组件，避免不必要的重新渲染');
        recommendations.push('检查useEffect的依赖项是否过多或不稳定');
      }
      
      if (renderCount > 20) {
        recommendations.push('可能存在无限渲染循环，检查状态更新逻辑');
        recommendations.push('考虑将状态提升或使用Context来减少prop drilling');
      }
    }

    return {
      componentName,
      renderCount,
      testDuration,
      passed,
      issues,
      recommendations,
    };
  }

  /**
   * 测试DataLineage组件的渲染性能
   */
  async testDataLineageRendering(): Promise<RenderingTestResult> {
    console.log('🧪 开始测试DataLineage组件渲染性能...');
    
    this.startMonitoring('DataLineage');
    
    // 等待组件加载和初始渲染完成
    await new Promise(resolve => setTimeout(resolve, 5000));
    
    // 模拟一些可能触发重新渲染的操作
    console.log('📊 模拟状态变化...');
    
    // 等待额外的渲染
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    const result = this.stopMonitoring('DataLineage');
    
    console.log('📋 DataLineage渲染性能测试结果:');
    console.log(`   渲染次数: ${result.renderCount}`);
    console.log(`   测试时长: ${result.testDuration}ms`);
    console.log(`   测试结果: ${result.passed ? '✅ 通过' : '❌ 失败'}`);
    
    if (result.issues.length > 0) {
      console.log('⚠️ 发现的问题:');
      result.issues.forEach(issue => console.log(`   - ${issue}`));
    }
    
    if (result.recommendations.length > 0) {
      console.log('💡 优化建议:');
      result.recommendations.forEach(rec => console.log(`   - ${rec}`));
    }
    
    return result;
  }

  /**
   * 清理测试环境
   */
  cleanup(): void {
    console.log = this.originalConsoleLog;
    this.renderCounts.clear();
  }
}

// 创建全局实例
export const renderingPerformanceTest = new RenderingPerformanceTest();

// 在开发环境下暴露到window对象
if (process.env.NODE_ENV === 'development') {
  (window as any).renderingPerformanceTest = renderingPerformanceTest;
}

// 便捷的测试函数
export const testDataLineagePerformance = () => {
  return renderingPerformanceTest.testDataLineageRendering();
};

// 自动测试函数（页面加载后自动运行）
export const autoTestDataLineagePerformance = () => {
  // 等待页面完全加载后再开始测试
  setTimeout(() => {
    testDataLineagePerformance().then(result => {
      if (!result.passed) {
        console.warn('⚠️ DataLineage组件性能测试未通过，建议进行优化');
      } else {
        console.log('🎉 DataLineage组件性能测试通过！');
      }
    });
  }, 1000);
};
